﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using HousingInfo.Library;

namespace WebHousingInfo
{
    public partial class DangTin : System.Web.UI.Page
    {
        private static NewsHouseBO newsHouseBO;
        private static LocationAdvertisementBO boqc;
        private static LocationAdvertisementDetailBO qcdetailbo;
        private static string option = null;
        private static OptionBO optionbo;
        private static string _fileImageName;
        private static string mode = null, modequangcao = null, modegiahan = null;
        private static bool checkqc = false;
        private static int location_parrent;
        private static string location_detail_inweb;
        private static string image1, image2, image3, image4, image5;
        private static bool checkreturn = true;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                //                    <asp:CollapsiblePanelExtender ExpandedImage="img/an.png"
                //CollapsedImage="img/hien.png" ImageControlID="imgBackgroundEmployeeDetail" SuppressPostBack="true" Collapsed="false" ID="CollapsiblePanelExtender1" TargetControlID="pn_content_detail" ExpandControlID="pn_title_detail" CollapseControlID="pn_title_detail" runat="server">
                //    </asp:CollapsiblePanelExtender>
                //<asp:RequiredFieldValidator ID="RequiredFieldValidator4" Display="None" runat="server" ControlToValidate="txtwidth"
                //                        ErrorMessage="<b>Lỗi nhập liệu</b><br />Yêu cầu nhập chiều rộng"></asp:RequiredFieldValidator>
                //                <asp:ValidatorCalloutExtender ID="RequiredFieldValidator4_ValidatorCalloutExtender" 
                //                    runat="server" TargetControlID="RequiredFieldValidator4">
                //                </asp:ValidatorCalloutExtender>
                //                <asp:RegularExpressionValidator Display="None" ID="RegularExpressionValidator5" runat="server" ControlToValidate="txtwidth"
                //                    ErrorMessage="Diện tích phải kiểu số" 
                //                    ValidationExpression="^\d+$"></asp:RegularExpressionValidator> 

                //                <asp:ValidatorCalloutExtender ID="RegularExpressionValidator5_ValidatorCalloutExtender" 
                //                    runat="server" Enabled="True" TargetControlID="RegularExpressionValidator5">
                //                </asp:ValidatorCalloutExtender>

                //lay thong tin lien he - chua login nen mac dinh la admin
                //string cvb = "," + "," + "," + ",";
                //var okokok = cvb.Split(',');    
                if (Session["UserName"] == null)
                    Response.Redirect("DangNhap.aspx");
                mode = Request.QueryString["id"];
                modequangcao = Request.QueryString["quangcao"];
                modegiahan = Request.QueryString["giahan"];
                RequiredAddress.Visible = false;
                RequiredWidth.Visible = false;
                RequiredHeight.Visible = false;
                RequiredPrice.Visible = false;
                if (modequangcao == "end")
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Đã kết thúc quảng cáo !')", true);
                }
                if (modegiahan == "true")
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                "alert('Gia hạn thành công !')", true);
                }
                getHouseType();
                getAreas();
                getCurrency();
                getCategoryHouse();
                getLocation();
                if (mode != null)
                {
                    lbtdangtin.Text = "SỬA TIN";
                    newsHouseBO = NewsHouseBO.GetNewsHouseBO(Convert.ToInt32(mode));
                    lblngaydang.Text = "<br /> (Ngày đăng: " + Convert.ToDateTime(newsHouseBO.CreatedDate).ToShortDateString() + ", " + "ngày hết hạn: " + Convert.ToDateTime(newsHouseBO.ExpireDate).ToShortDateString() + ", " + "ngày chỉnh sửa gần nhất " + Convert.ToDateTime(newsHouseBO.UpdatedDate).ToShortDateString() + ")";
                    lblngaydang.Visible = true;
                    if (newsHouseBO.IsActive == true)
                        btnketthuc.Visible = true;
                    dlcategoryhouse.SelectedValue = newsHouseBO.CategoryID.ToString();
                    dlhousetype.SelectedValue = newsHouseBO.HousingTypeID.ToString();
                    dlareas.SelectedValue = newsHouseBO.AreaID.ToString();
                    dlareas_SelectedIndexChanged(sender, e);
                    dlareadetail.SelectedValue = newsHouseBO.AreaDetailID.ToString();
                    lblsolangiahanhai.Text = newsHouseBO.NumExtension.ToString();
                    txtaddress.Text = newsHouseBO.HousesAddress;
                    if (newsHouseBO.Message != "")
                    {
                        pn_result.Visible = true;
                        lblthongbao.Text = newsHouseBO.Message;
                    }
                    if (newsHouseBO.SurfaceAreaWidth == -1)
                    {
                        txtwidth.Text = "";
                    }
                    else txtwidth.Text = newsHouseBO.SurfaceAreaWidth.ToString();
                    if (newsHouseBO.SurfaceAreaHeight == -1)
                        txtheight.Text = "";
                    else txtheight.Text = newsHouseBO.SurfaceAreaHeight.ToString();
                    dlDirection.SelectedValue = newsHouseBO.Direction;
                    if (newsHouseBO.Price == -1)
                        txtprice.Text = "";
                    else txtprice.Text = newsHouseBO.Price.ToString();
                    dlcurrency.SelectedValue = newsHouseBO.CurrencyID.ToString();
                    cbmv.Checked = Convert.ToBoolean(newsHouseBO.SupM);
                    cbthuongluong.Checked = newsHouseBO.IsNegotiation;
                    dltimepost.SelectedValue = (newsHouseBO.ExpireDate - newsHouseBO.CreatedDate).Days.ToString();
                    dltimepost.Enabled = false;
                    txttitle.Text = newsHouseBO.Title;
                    txtmota.Text = newsHouseBO.NewsContent;
                    if (newsHouseBO.UrlImage != "")
                    {
                        lbtaddimage.Text = "| Thêm Hình";
                        var array_listImage = newsHouseBO.UrlImage.Split('/');
                        int numimage = array_listImage.Count();
                        lbt_huy_extract_image1.Visible = false;
                        if (numimage > 0)
                        {
                            pn_Extract_Image.Visible = true;
                            upload_one_image.Visible = false;
                            upload_extract_image1.Visible = false;
                            upload_extract_image2.Visible = false;
                            upload_extract_image3.Visible = false;
                            upload_extract_image4.Visible = false;
                        }
                        if (numimage == 5)
                        {
                            lbtaddimage.Visible = false;
                        }
                        try
                        {
                            txtimage1.Text = array_listImage[0].ToString();
                            txtimage1.Visible = true;
                            lbtchangeimage1.Visible = true;
                            image1 = array_listImage[0];
                            txtimage2.Text = array_listImage[1].ToString();
                            txtimage2.Visible = true;
                            lbtchangeimage2.Visible = true;
                            image2 = array_listImage[1];
                            txtimage3.Text = array_listImage[2].ToString();
                            txtimage3.Visible = true;
                            lbtchangeimage3.Visible = true;
                            image3 = array_listImage[3];
                            txtimage4.Text = array_listImage[3].ToString();
                            txtimage4.Visible = true;
                            lbtchangeimage4.Visible = true;
                            image4 = array_listImage[4];
                            txtimage5.Text = array_listImage[4].ToString();
                            txtimage5.Visible = true;
                            lbtchangeimage5.Visible = true;
                            image5 = array_listImage[5];
                        }
                        catch { }
                    }
                    var listaddons = newsHouseBO.Addons.Split(',');
                    txtbuidyear.Text = listaddons[0].ToString();
                    txtnhatam_vesinh.Text = listaddons[1].ToString();
                    txtso_phongngu.Text = listaddons[2].ToString();
                    cbnuocmay.Checked = Convert.ToBoolean(listaddons[3]);
                    cbdonghodien.Checked = Convert.ToBoolean(listaddons[4]);
                    txtduongtruocnha.Text = listaddons[5].ToString();

                    var listInteriorAmenities = newsHouseBO.InteriorAmenities.Split(',');
                    cbthangmay.Checked = Convert.ToBoolean(listInteriorAmenities[0]);
                    cbbaove.Checked = Convert.ToBoolean(listInteriorAmenities[1]);
                    cbdauoto.Checked = Convert.ToBoolean(listInteriorAmenities[2]);
                    cbsanvuon.Checked = Convert.ToBoolean(listInteriorAmenities[3]);
                    cbdieuhoa.Checked = Convert.ToBoolean(listInteriorAmenities[4]);
                    cbsanthuong.Checked = Convert.ToBoolean(listInteriorAmenities[5]);
                    cbdienthoai.Checked = Convert.ToBoolean(listInteriorAmenities[6]);
                    cbhoboi.Checked = Convert.ToBoolean(listInteriorAmenities[7]);
                    cbnhabep.Checked = Convert.ToBoolean(listInteriorAmenities[8]);
                    cbgaraoto.Checked = Convert.ToBoolean(listInteriorAmenities[9]);
                    cbphongkhach.Checked = Convert.ToBoolean(listInteriorAmenities[10]);

                    var list_SocialCulture = newsHouseBO.SocialCulture.Split(',');
                    cbcongvien.Checked = Convert.ToBoolean(list_SocialCulture[0]);
                    cbtrungtam_giaitri.Checked = Convert.ToBoolean(list_SocialCulture[1]);
                    cbmaugiao.Checked = Convert.ToBoolean(list_SocialCulture[2]);
                    cbtrungtam_thuongmai.Checked = Convert.ToBoolean(list_SocialCulture[3]);
                    cbdh_cd.Checked = Convert.ToBoolean(list_SocialCulture[4]);
                    cbbenhvien.Checked = Convert.ToBoolean(list_SocialCulture[5]);
                    cbcapba.Checked = Convert.ToBoolean(list_SocialCulture[6]);
                    cbcho.Checked = Convert.ToBoolean(list_SocialCulture[7]);
                    cbcaphai.Checked = Convert.ToBoolean(list_SocialCulture[8]);
                    cbkinhdoanh.Checked = Convert.ToBoolean(list_SocialCulture[9]);
                    cbcapmot.Checked = Convert.ToBoolean(list_SocialCulture[10]);
                    cbkhudantri.Checked = Convert.ToBoolean(list_SocialCulture[11]);

                    if (newsHouseBO.Documents == "Giấy Tay")
                        rdgiaytay.Checked = true;
                    else if (newsHouseBO.Documents == "Sổ Hồng")
                        rdsohong.Checked = true;
                    else if (newsHouseBO.Documents == "Sổ Đỏ")
                        rdsodo.Checked = true;

                    txtcontactname.Text = newsHouseBO.ContactName;
                    txtcontactaddress.Text = newsHouseBO.ContactAddress;
                    txtcontactEmail.Text = newsHouseBO.ContactEmail;
                    txtcontactphone.Text = newsHouseBO.ContactPhone;
                    if (newsHouseBO.IsAdvertisement == true)
                    {
                        btndong.Visible = false;
                        btnketthuc_qc.Visible = true;
                        checkqc = true;
                        pn_quangcao.Visible = true;
                        getLocation();
                        try
                        {
                            LocationAdvertisementDetailBO adversiter = LocationAdvertisementDetailBO.GetAdvertisementDetaiBO_ByIDNewsHouses(newsHouseBO.NewsHouseID);
                            dlkhuvuc_qc.SelectedValue = adversiter.LocationAdversitementID.ToString();
                            changeChiTietQuangCao();
                            dlchitiet.Items.Insert(0, adversiter.LocationInWeb.ToString());
                            dlchitiet.SelectedValue = adversiter.LocationInWeb.ToString();
                            //luu lai gia tri quang cao cua tin
                            location_parrent = Convert.ToInt32(adversiter.LocationAdversitementID);
                            location_detail_inweb = adversiter.LocationInWeb;
                        }
                        catch { }
                        upload_image_qc.Visible = false;
                        txtimage_qc.Visible = true;
                        txtimage_qc.Text = newsHouseBO.UrlImageAdversitement;
                        lbtImageQC.Visible = true;
                    }
                    else checkqc = false;
                    btndangtin.Visible = false;
                    btlsuatin.Visible = true;
                    btnxemtruoc.Visible = false;
                    if (newsHouseBO.ExpireDate <= DateTime.Now)
                    {
                        OptionBO optionbogiahan;
                        optionbogiahan = OptionBO.GetNameOptionBO("SoLanGiaHanTinNhaDat");

                        if (Convert.ToInt32(optionbogiahan.OptionValue) <= newsHouseBO.NumExtension)
                        {
                            pn_khongduocgiahan.Visible = true;
                            pn_thongbaohethan.Visible = false;
                        }
                        else
                        {
                            pn_thongbaohethan.Visible = true;
                            pn_khongduocgiahan.Visible = false;
                        }                        
                        btlsuatin.Visible = false;
                    }
                }
                else
                {
                    btndangtin.Visible = true;
                    btlsuatin.Visible = false;
                    btnxoa.Visible = false;
                    lbtaddimage.Text = "Thêm Hình";
                    try
                    {
                        UserBO userBO = UserBO.GetUserBO(Session["UserName"].ToString());
                        txtcontactname.Text = userBO.FullName;
                        txtcontactaddress.Text = userBO.Address;
                        txtcontactEmail.Text = userBO.Email;
                        txtcontactphone.Text = userBO.TelePhone;
                    }
                    catch { }
                    //end                    
                }
            }
        }

        public NewsHouseBO GetNewsHouse()
        {
            NewsHouseBO nhbo;
            try
            {
                if (mode != null)
                {
                    nhbo = NewsHouseBO.GetNewsHouseBO(int.Parse(mode));
                    return nhbo;
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }
        }

        private void getHouseType()
        {
            try
            {
                var housingType = HousingTypeInfo.GetHousingTypeInfo();
                dlhousetype.DataSource = housingType;
                dlhousetype.DataBind();
            }
            catch { }
        }

        private void getCategoryHouse()
        {
            try
            {
                var categoryHouse = CategoryInfo.GetCategoryInfo_BySingle(true, false, false, false, true);
                dlcategoryhouse.DataSource = categoryHouse;
                dlcategoryhouse.DataBind();
            }
            catch { }
        }

        private void getAreas()
        {
            try
            {
                var areas = AreaInfo.GetAreaInfo();
                if (areas != null)
                {
                    dlareas.DataSource = areas;
                    dlareas.DataBind();
                    //lay danh sach khu vuc con
                    var areaId = areas[0].Key.ToString();
                    getAreaDetailWithAreaId(areaId);
                }
            }
            catch { }
        }
        private void getAreaDetailWithAreaId(string areaId)
        {
            try
            {
                var areadetailList = AreaDetailInfo.GetAreaDetailInfo(int.Parse(areaId));
                dlareadetail.DataSource = areadetailList;
                dlareadetail.DataBind();
            }
            catch (Exception)
            {

            }

        }

        private void getCurrency()
        {
            try
            {
                var currenyInfo = CurrencyInfo.GetCurrencyInfo();
                dlcurrency.DataSource = currenyInfo;
                dlcurrency.DataBind();
            }
            catch
            { }
        }

        private void getLocation()
        {
            try
            {
                var locationInfo = LocationAdvertisementInfo.GetLocationAdvertisementInfo();
                dlkhuvuc_qc.DataSource = locationInfo;
                dlkhuvuc_qc.DataBind();
                changeChiTietQuangCao();
            }
            catch
            { }
        }

        protected void dlareas_SelectedIndexChanged(object sender, EventArgs e)
        {
            var areaId = dlareas.SelectedValue;
            getAreaDetailWithAreaId(areaId);
        }

        protected void btndangtin_Click(object sender, EventArgs e)
        {
            if (Session["UserName"] == null)
                Response.Redirect("DangNhap.aspx");
            newsHouseBO = NewsHouseBO.NewNewsHouseBO();
            newsHouseBO.UserName = Session["UserName"].ToString();
            newsHouseBO.AreaDetailID = Convert.ToInt32(dlareadetail.SelectedValue);
            newsHouseBO.CategoryID = Convert.ToInt32(dlcategoryhouse.SelectedValue);
            newsHouseBO.CurrencyID = Convert.ToInt32(dlcurrency.SelectedValue);
            newsHouseBO.HousingTypeID = Convert.ToInt32(dlhousetype.SelectedValue);
            if (rdsodo.Checked == true)
            {
                newsHouseBO.Documents = "Sổ Đỏ";
            }
            else if (rdsohong.Checked == true)
            {
                newsHouseBO.Documents = "Sổ Hồng";
            }
            else if (rdgiaytay.Checked == true)
            {
                newsHouseBO.Documents = "Giấy Tay";
            }
            if (txtwidth.Text != "")
            {
                newsHouseBO.SurfaceAreaWidth = Convert.ToInt32(txtwidth.Text);
            }
            else newsHouseBO.SurfaceAreaWidth = -1;
            if (txtheight.Text != "")
            {
                newsHouseBO.SurfaceAreaHeight = Convert.ToInt32(txtheight.Text);
            }
            else newsHouseBO.SurfaceAreaHeight = -1;
            newsHouseBO.SupM = cbmv.Checked;
            newsHouseBO.HousesAddress = txtaddress.Text;
            newsHouseBO.Direction = dlDirection.SelectedValue;
            if (txtprice.Text != "")
            {
                newsHouseBO.Price = decimal.Parse(txtprice.Text);
            }
            else newsHouseBO.Price = -1;
            newsHouseBO.IsNegotiation = cbthuongluong.Checked;
            newsHouseBO.CreatedDate = DateTime.Now;
            newsHouseBO.PostDate = DateTime.Now;
            newsHouseBO.UpdatedDate = DateTime.Now;
            newsHouseBO.ExpireDate = DateTime.Now.AddDays(double.Parse(dltimepost.SelectedValue));
            newsHouseBO.Title = txttitle.Text;
            newsHouseBO.NewsContent = txtmota.Text;
            //upload anh
            checkreturn = true;
            if (upload_one_image.FileName.Length > 0)
            {
                postImage(upload_one_image, "", "");
                if (checkreturn == false) return;
            }
            if (upload_extract_image1.FileName.Length > 0)
            {
                postImage(upload_extract_image1, "", "");
                if (checkreturn == false) return;
            }
            if (upload_extract_image2.FileName.Length > 0)
            {
                postImage(upload_extract_image2, "", "");
                if (checkreturn == false) return;
            }
            if (upload_extract_image3.FileName.Length > 0)
            {
                postImage(upload_extract_image3, "", "");
                if (checkreturn == false) return;
            }
            if (upload_extract_image4.FileName.Length > 0)
            {
                postImage(upload_extract_image4, "", "");
                if (checkreturn == false) return;
            }
            newsHouseBO.ViewCount = 0;
            newsHouseBO.IsExtension = false;
            newsHouseBO.NumExtension = 0;
            newsHouseBO.IsPremium = false;
            newsHouseBO.IsAdvertisement = false;
            if (pn_quangcao.Visible == true)
            {
                if (dlchitiet.SelectedValue == "")
                {
                    deleteListImage();
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn hoặc đã hết vị trí quảng cáo !!!')", true);
                    upload_image_qc.Focus();
                    return;
                }
                if (upload_image_qc.FileName.Length > 0)
                {
                    postImageQuangCao(upload_image_qc, "");
                    if (checkreturn == false) return;
                    newsHouseBO.IsPremium = true;
                    newsHouseBO.IsAdvertisement = true;
                }
                else
                {
                    deleteListImage();
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn ảnh quảng cáo !!!')", true);
                    upload_image_qc.Focus();
                    return;
                }
            }
            newsHouseBO.IsActive = false;
            newsHouseBO.NumPost = 0;
            newsHouseBO.IsContact = true;
            newsHouseBO.ContactName = txtcontactname.Text;
            newsHouseBO.ContactAddress = txtcontactaddress.Text;
            newsHouseBO.ContactEmail = txtcontactEmail.Text;
            newsHouseBO.ContactPhone = txtcontactphone.Text;
            string addons = "", interiorAmenities = "", socialCulture = "";
            addons += txtbuidyear.Text + ",";
            addons += txtnhatam_vesinh.Text + ",";
            addons += txtso_phongngu.Text + ",";
            addons += cbnuocmay.Checked.ToString() + ",";
            addons += cbdonghodien.Checked.ToString() + ",";
            addons += txtduongtruocnha.Text;
            newsHouseBO.Addons = addons;
            string generation_idnewsHouses;
            generation_idnewsHouses = ImageFileName(newsHouseBO.UserName);
            newsHouseBO.Temp = generation_idnewsHouses;
            interiorAmenities += cbthangmay.Checked.ToString() + ",";
            interiorAmenities += cbbaove.Checked.ToString() + ",";
            interiorAmenities += cbdauoto.Checked.ToString() + ",";
            interiorAmenities += cbsanvuon.Checked.ToString() + ",";
            interiorAmenities += cbdieuhoa.Checked.ToString() + ",";
            interiorAmenities += cbsanthuong.Checked.ToString() + ",";
            interiorAmenities += cbdienthoai.Checked.ToString() + ",";
            interiorAmenities += cbhoboi.Checked.ToString() + ",";
            interiorAmenities += cbnhabep.Checked.ToString() + ",";
            interiorAmenities += cbgaraoto.Checked.ToString() + ",";
            interiorAmenities += cbphongkhach.Checked.ToString();
            newsHouseBO.InteriorAmenities = interiorAmenities;
            socialCulture += cbcongvien.Checked.ToString() + ",";
            socialCulture += cbtrungtam_giaitri.Checked.ToString() + ",";
            socialCulture += cbmaugiao.Checked.ToString() + ",";
            socialCulture += cbtrungtam_thuongmai.Checked.ToString() + ",";
            socialCulture += cbdh_cd.Checked.ToString() + ",";
            socialCulture += cbbenhvien.Checked.ToString() + ",";
            socialCulture += cbcapba.Checked.ToString() + ",";
            socialCulture += cbcho.Checked.ToString() + ",";
            socialCulture += cbcaphai.Checked.ToString() + ",";
            socialCulture += cbkinhdoanh.Checked.ToString() + ",";
            socialCulture += cbcapmot.Checked.ToString() + ",";
            socialCulture += cbkhudantri.Checked.ToString();
            newsHouseBO.SocialCulture = socialCulture;            
            if (OptionBO.GetNameOptionBO("tudongduyettinmoi").OptionValue == "True")
                newsHouseBO.IsActive = true;
            bool checkcp = false;
            try
            {
                newsHouseBO.Save();
                if (pn_quangcao.Visible == true)
                {
                    NewsHouseBO newsHouseUrl;
                    newsHouseUrl = NewsHouseBO.GetNewsHouseBO_ByTemp(generation_idnewsHouses);
                    boqc = LocationAdvertisementBO.GetLocationAdvertisementBO(Convert.ToInt32(dlkhuvuc_qc.SelectedValue));
                    qcdetailbo = boqc.LocationAdvertisementDetailBOList.Single(a => a.LocationInWeb == dlchitiet.SelectedValue);
                    qcdetailbo.NewsHouseID = newsHouseUrl.NewsHouseID;
                    boqc.Save();
                    changeChiTietQuangCao();
                }
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Đăng tin thành công !')", true);
                checkcp = true;
                
            }
            catch
            {
                deleteListImage();
                deleteExitsImage(newsHouseBO.UrlImageAdversitement);
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Đăng tin thất bại !')", true);
            }
            if(checkcp == true)
                Response.Redirect("DangTinVip.aspx?id=" + NewsHouseBO.GetNewsHouseBO_ByTemp(generation_idnewsHouses).NewsHouseID);
            return;
        }

        private void postImage(FileUpload filename, string filedelete, string numimage)
        {
            try
            {
                if (filename.HasFile)
                {
                    if (filename.FileBytes.Length < 1048576)
                    {
                        _fileImageName = filename.FileName.Replace(" ", "_");

                        string formatFile = Path.GetExtension(_fileImageName);
                        //kiem tra dinh dang cho phep upload
                        if (formatFile.Equals(".jpg") || formatFile.Equals(".gif") || formatFile.Equals(".png") || formatFile.Equals(".JPG") || formatFile.Equals(".GIF") || formatFile.Equals(".PNG") || formatFile.Equals(".JPEG") || formatFile.Equals(".jpeg"))
                        {
                            //kiem tra file da ton tai
                            string filePath = HttpContext.Current.Server.MapPath("TotalUpload/ImagesTotal/" + _fileImageName);
                            if (File.Exists(filePath))
                            {
                                //neu ton tai thi doi ten
                                _fileImageName = ImageFileName(_fileImageName);
                            }
                            //thuc hien luu file
                            try
                            {
                                filename.SaveAs(Server.MapPath("TotalUpload/ImagesTotal/" + _fileImageName));
                                //deleteExitsImage(txtlink.Text);
                                //txtlink.Text = _fileImageName;
                                try
                                {
                                    if (newsHouseBO.UrlImage != "")
                                    {
                                        newsHouseBO.UrlImage += "/" + _fileImageName;
                                    }
                                    else newsHouseBO.UrlImage = _fileImageName;
                                }
                                catch
                                {
                                    newsHouseBO.UrlImage = "";
                                }
                            }
                            catch (Exception)
                            {
                                deleteListImage();
                                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Có một số vấn đề xả ra trong khi lưu. Xin hay thử lại.')", true);
                                checkreturn = false;
                                return;
                            }
                        }
                        else
                        {
                            deleteListImage();
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chỉ được upload các định dạng ảnh (.jpg , .gif, .png)')", true);
                            checkreturn = false;
                            return;
                        }
                    }
                    else
                    {
                        deleteListImage();
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Kích thước ảnh không quá 1MB.')", true);
                        checkreturn = false;
                        return;
                    }
                }
                else
                {
                    deleteListImage();
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chưa chọn ảnh. !')", true);
                    checkreturn = false;
                    return;
                }
            }
            catch { }
        }

        private static string ImageFileName(string fileName)
        {
            Random r = new Random();
            return r.Next(0, 10000).ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + fileName;
        }

        private void deleteListImage()
        {
            string listImage = newsHouseBO.UrlImage;
            var arraylist = listImage.Split('/');
            foreach (var detail in arraylist)
            {
                deleteExitsImage(detail);
            }
        }

        private void deleteExitsImage(string filedelete)
        {
            try
            {
                var pathFileImage = Server.MapPath("TotalUpload/ImagesTotal/" + filedelete);
                FileInfo fileInfo;
                if (File.Exists(pathFileImage))
                {
                    fileInfo = new FileInfo(pathFileImage);
                    fileInfo.Delete();
                }
            }
            catch
            {
            }
        }

        private void postImageQuangCao(FileUpload filename, string filedelete)
        {
            try
            {
                if (filename.HasFile)
                {
                    if (filename.FileBytes.Length < 1048576)
                    {
                        _fileImageName = filename.FileName.Replace(" ", "_");

                        string formatFile = Path.GetExtension(_fileImageName);
                        //kiem tra dinh dang cho phep upload
                        if (formatFile.Equals(".jpg") || formatFile.Equals(".gif") || formatFile.Equals(".png") || formatFile.Equals(".JPG") || formatFile.Equals(".GIF") || formatFile.Equals(".PNG"))
                        {
                            //kiem tra file da ton tai
                            string filePath = HttpContext.Current.Server.MapPath("TotalUpload/ImagesTotal/" + _fileImageName);
                            if (File.Exists(filePath))
                            {
                                //neu ton tai thi doi ten
                                _fileImageName = ImageFileName(_fileImageName);
                            }
                            //thuc hien luu file
                            try
                            {
                                filename.SaveAs(Server.MapPath("TotalUpload/ImagesTotal/" + _fileImageName));
                                //deleteExitsImage(txtlink.Text);
                                //txtlink.Text = _fileImageName;
                                try
                                {
                                    newsHouseBO.UrlImageAdversitement = _fileImageName;
                                }
                                catch
                                {
                                    newsHouseBO.UrlImage = "";
                                }
                            }
                            catch (Exception)
                            {
                                deleteListImage();
                                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Có một số vấn đề xả ra trong khi lưu. Xin hay thử lại.')", true);
                                checkreturn = false;
                                return;
                            }
                        }
                        else
                        {
                            deleteListImage();
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chỉ được upload các định dạng ảnh (.jpg , .gif, .png)')", true);
                            checkreturn = false;
                            return;
                        }
                    }
                    else
                    {
                        deleteListImage();
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Kích thước ảnh không quá 1MB.')", true);
                        checkreturn = false;
                        return;
                    }
                }
                else
                {
                    deleteListImage();
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chưa chọn file ảnh. !')", true);
                    checkreturn = false;
                    return;
                }
            }
            catch { }
        }

        protected void btntrove_Click(object sender, EventArgs e)
        {
            Response.Redirect("QuanLyCaNhan.aspx");
        }

        protected void lbtdangtin_qc_Click(object sender, EventArgs e)
        {
            pn_quangcao.Visible = true;
            getLocation();
            btndong.Focus();
        }

        protected void dlkhuvuc_qc_SelectedIndexChanged(object sender, EventArgs e)
        {
            changeChiTietQuangCao();
            if (checkqc == true)
            {
                if (Convert.ToInt32(dlkhuvuc_qc.SelectedValue) == location_parrent)
                {
                    dlchitiet.Items.Insert(0, location_detail_inweb);
                    dlchitiet.SelectedValue = location_detail_inweb;
                }
            }
        }

        private void changeChiTietQuangCao()
        {
            option = null;
            string vitridaco = "";
            string vitrichuaco = "";
            lblthongtinquangcao.Text = "";
            int idqc;
            idqc = Convert.ToInt32(dlkhuvuc_qc.SelectedValue);
            if (idqc == 1)
            {
                option = "SoViTriQCTren";
                lblthongtinquangcao.Text = "Chi tiết:<br />+ Dưới Banner của trang web<br />+Tổng cộng có ";
            }
            else if (idqc == 2)
            {
                option = "SoViTriQCTrai";
                lblthongtinquangcao.Text = "Chi tiết:<br />+ Cột bên trái của trang web<br />+Tổng cộng có ";
            }
            else if (idqc == 3)
            {
                option = "SoViTriQCPhai";
                lblthongtinquangcao.Text = "Chi tiết:<br />+ Cột bên phải của trang web<br />+Tổng cộng có ";
            }
            dlchitiet.Items.Clear();
            try
            {
                optionbo = OptionBO.GetNameOptionBO(option);
            }
            catch
            {
                optionbo = null;
            }
            if (optionbo != null)
            {
                lblthongtinquangcao.Text += "<span>" + Convert.ToInt32(optionbo.OptionValue) + "</span>" + " vị trí cho phép đăng quảng cáo";
                boqc = LocationAdvertisementBO.GetLocationAdvertisementBO(idqc);
                for (int i = 1; i <= Convert.ToInt32(optionbo.OptionValue); i++)
                {
                    try
                    {
                        qcdetailbo = boqc.LocationAdvertisementDetailBOList.Single(a => a.LocationInWeb == i.ToString());
                    }
                    catch
                    {
                        qcdetailbo = null;
                    }
                    if (qcdetailbo != null && qcdetailbo.IsActive == true)
                    {
                        if (qcdetailbo.NewsHouseID == null)
                        {
                            dlchitiet.Items.Add(i.ToString());
                            if (vitrichuaco == "")
                            {
                                vitrichuaco = i.ToString();
                            }
                            else vitrichuaco += ", " + i.ToString();
                        }
                        else
                        {
                            if (vitridaco == "")
                            {
                                vitridaco += i.ToString() + " <a class='xemtindaquangcao' href='TinNhaDatChiTiet.aspx?id=" + qcdetailbo.NewsHouseID +"'>Xem</a>";
                            }
                            else vitridaco += ", " + i.ToString() + " <a class='xemtindaquangcao' href='TinNhaDatChiTiet.aspx?id=" + qcdetailbo.NewsHouseID + "'>Xem</a>";
                        }
                    }
                }
                lblthongtinquangcao.Text += "<br />+Các Vị trí đã được đăng tin quảng cáo: " + vitridaco + "<br />+Các vị trí còn trống: " + vitrichuaco;
            }
        }

        protected void lbtaddimage_Click(object sender, EventArgs e)
        {
            if (mode != null)
            {
                pn_Extract_Image.Visible = true;
                if (txtimage2.Visible == false)
                    upload_extract_image1.Visible = true;
                if (txtimage3.Visible == false)
                    upload_extract_image2.Visible = true;
                if (txtimage4.Visible == false)
                    upload_extract_image3.Visible = true;
                if (txtimage5.Visible == false)
                    upload_extract_image4.Visible = true;
            }
            else
            {
                pn_Extract_Image.Visible = true;
                lbt_huy_extract_image1.Focus();
            }
        }

        protected void lbt_huy_extract_image1_Click(object sender, EventArgs e)
        {
            pn_Extract_Image.Visible = false;
            lbtaddimage.Focus();
        }

        protected void btndong_Click(object sender, EventArgs e)
        {
            pn_quangcao.Visible = false;
        }

        protected void btnketthuc_qc_Click(object sender, EventArgs e)
        {
            //tin nay dang dang ky quang cao - thuc hien thoi quang cao
            qcdetailbo = LocationAdvertisementDetailBO.GetAdvertisementDetaiBO_ByIDNewsHouses(newsHouseBO.NewsHouseID);
            boqc = LocationAdvertisementBO.GetLocationAdvertisementBO(Convert.ToInt32(qcdetailbo.LocationAdversitementID));
            qcdetailbo = boqc.LocationAdvertisementDetailBOList.Single(a => a.NewsHouseID == newsHouseBO.NewsHouseID);
            qcdetailbo.NewsHouseID = null;
            boqc.Save();
            NewsHouseBO newsHouse;
            newsHouse = NewsHouseBO.GetNewsHouseBO(Convert.ToInt32(mode));
            newsHouse.IsAdvertisement = false;
            deleteExitsImage(newsHouse.UrlImageAdversitement);
            newsHouse.UrlImageAdversitement = "";
            btndong.Visible = true;
            try
            {
                newsHouse.Save();
                checkqc = false;
                Response.Redirect("DangTin.aspx?id=" + mode + "&quangcao=end");                
            }
            catch
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Kết thúc quảng cáo thất bại !')", true);
                return;

            }
        }

        protected void lbtchangeimage1_Click(object sender, EventArgs e)
        {
            txtimage1.Visible = false;
            upload_one_image.Visible = true;
            lbtchangeimage1.Visible = false;
            lbtaddimage.Text = "Thêm Hình";
        }

        protected void lbtchangeimage2_Click(object sender, EventArgs e)
        {
            txtimage2.Visible = false;
            upload_extract_image1.Visible = true;
            lbtchangeimage2.Visible = false;
        }

        protected void lbtchangeimage3_Click(object sender, EventArgs e)
        {
            txtimage3.Visible = false;
            upload_extract_image2.Visible = true;
            lbtchangeimage3.Visible = false;
        }

        protected void lbtchangeimage4_Click(object sender, EventArgs e)
        {
            txtimage4.Visible = false;
            upload_extract_image3.Visible = true;
            lbtchangeimage4.Visible = false;
        }

        protected void lbtchangeimage5_Click(object sender, EventArgs e)
        {
            txtimage5.Visible = false;
            upload_extract_image4.Visible = true;
            lbtchangeimage5.Visible = false;
        }

        protected void lbtImageQC_Click(object sender, EventArgs e)
        {
            txtimage_qc.Visible = false;
            upload_image_qc.Visible = true;
            lbtImageQC.Visible = false;
        }

        protected void btlsuatin_Click(object sender, EventArgs e)
        {
            if (Session["UserName"] == null)
                Response.Redirect("DangNhap.aspx");
            newsHouseBO = NewsHouseBO.GetNewsHouseBO(Convert.ToInt32(mode));
            newsHouseBO.UserName = Session["UserName"].ToString();
            newsHouseBO.AreaDetailID = Convert.ToInt32(dlareadetail.SelectedValue);
            newsHouseBO.CategoryID = Convert.ToInt32(dlcategoryhouse.SelectedValue);
            newsHouseBO.CurrencyID = Convert.ToInt32(dlcurrency.SelectedValue);
            newsHouseBO.HousingTypeID = Convert.ToInt32(dlhousetype.SelectedValue);
            if (rdsodo.Checked == true)
            {
                newsHouseBO.Documents = "Sổ Đỏ";
            }
            else if (rdsohong.Checked == true)
            {
                newsHouseBO.Documents = "Sổ Hồng";
            }
            else if (rdgiaytay.Checked == true)
            {
                newsHouseBO.Documents = "Giấy Tay";
            }
            if (txtwidth.Text != "")
            {
                newsHouseBO.SurfaceAreaWidth = Convert.ToInt32(txtwidth.Text);
            }
            else
            {
                newsHouseBO.SurfaceAreaWidth = -1;
            }
            if (txtheight.Text != "")
            {
                newsHouseBO.SurfaceAreaHeight = Convert.ToInt32(txtheight.Text);
            }
            else
            {
                newsHouseBO.SurfaceAreaHeight = -1;
            }
            newsHouseBO.SupM = cbmv.Checked;
            newsHouseBO.HousesAddress = txtaddress.Text;
            newsHouseBO.Direction = dlDirection.SelectedValue;
            if (txtprice.Text != "")
            {
                newsHouseBO.Price = decimal.Parse(txtprice.Text);
            }
            else
            {
                newsHouseBO.Price = -1;
            }
            newsHouseBO.IsNegotiation = cbthuongluong.Checked;
            newsHouseBO.UpdatedDate = DateTime.Now;
            newsHouseBO.Title = txttitle.Text;
            newsHouseBO.NewsContent = txtmota.Text;

            dltimepost.Enabled = false;
            //upload anh
            newsHouseBO.UrlImage = "";
            checkreturn = true;
            if (upload_one_image.Visible == true)
            {
                deleteExitsImage(txtimage1.Text);
                if (upload_one_image.FileName.Length > 0)
                {
                    postImage(upload_one_image, "", "");
                    if (checkreturn == false) return;
                }
            }
            else if (txtimage1.Visible == true)
            {
                if (newsHouseBO.UrlImage == "")
                {
                    newsHouseBO.UrlImage = txtimage1.Text;
                }
                else
                {
                    newsHouseBO.UrlImage += "/" + txtimage1.Text;
                }
            }
            if (upload_extract_image1.Visible == true)
            {
                deleteExitsImage(txtimage2.Text);
                if (upload_extract_image1.FileName.Length > 0)
                {
                    postImage(upload_extract_image1, "", "");
                    if (checkreturn == false) return;
                }
            }
            else if (txtimage2.Visible == true)
            {
                if (newsHouseBO.UrlImage == "")
                {
                    newsHouseBO.UrlImage = txtimage2.Text;
                }
                else
                {
                    newsHouseBO.UrlImage += "/" + txtimage2.Text;
                }
            }
            if (upload_extract_image2.Visible == true)
            {
                deleteExitsImage(txtimage3.Text);
                if (upload_extract_image2.FileName.Length > 0)
                {
                    postImage(upload_extract_image2, "", "");
                    if (checkreturn == false) return;
                }
            }
            else if (txtimage3.Visible == true)
            {
                if (newsHouseBO.UrlImage == "")
                {
                    newsHouseBO.UrlImage = txtimage3.Text;
                }
                else
                {
                    newsHouseBO.UrlImage += "/" + txtimage3.Text;
                }
            }
            if (upload_extract_image3.Visible == true)
            {
                deleteExitsImage(txtimage4.Text);
                if (upload_extract_image3.FileName.Length > 0)
                {
                    postImage(upload_extract_image3, "", "");
                    if (checkreturn == false) return;
                }
            }
            else if (txtimage4.Visible == true)
            {
                if (newsHouseBO.UrlImage == "")
                {
                    newsHouseBO.UrlImage = txtimage4.Text;
                }
                else
                {
                    newsHouseBO.UrlImage += "/" + txtimage4.Text;
                }
            }
            if (upload_extract_image4.Visible == true)
            {
                deleteExitsImage(txtimage5.Text);
                if (upload_extract_image4.FileName.Length > 0)
                {
                    postImage(upload_extract_image4, "", "");
                    if (checkreturn == false) return;
                }
            }
            else if (txtimage5.Visible == true)
            {
                if (newsHouseBO.UrlImage == "")
                {
                    newsHouseBO.UrlImage = txtimage5.Text;
                }
                else
                {
                    newsHouseBO.UrlImage += "/" + txtimage5.Text;
                }
            }
            if (pn_quangcao.Visible == true)
            {
                if (newsHouseBO.IsAdvertisement == true)
                {
                    if (upload_image_qc.Visible == true)
                    {
                        if (dlchitiet.SelectedValue == "")
                        {
                            //deleteListImage();
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn hoặc đã hết vị trí quảng cáo !!!')", true);
                            upload_image_qc.Focus();
                            return;
                        }
                        if (upload_image_qc.FileName.Length > 0)
                        {
                            postImageQuangCao(upload_image_qc, "");
                            if (checkreturn == false) return;
                            deleteExitsImage(txtimage_qc.Text);
                            //newsHouseBO.IsPremium = true;
                            //newsHouseBO.IsAdvertisement = true;
                        }
                        else
                        {
                            //deleteListImage();
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn ảnh quảng cáo !!!')", true);
                            upload_image_qc.Focus();
                            return;
                        }
                    }
                }
                else
                {
                    if (dlchitiet.SelectedValue == "")
                    {
                        //deleteListImage();
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn hoặc đã hết vị trí quảng cáo !!!')", true);
                        upload_image_qc.Focus();
                        return;
                    }
                    if (upload_image_qc.FileName.Length > 0)
                    {
                        postImageQuangCao(upload_image_qc, "");
                        if (checkreturn == false) return;
                        newsHouseBO.IsPremium = true;
                        newsHouseBO.IsAdvertisement = true;
                    }
                    else
                    {
                        //deleteListImage();
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn ảnh quảng cáo !!!')", true);
                        upload_image_qc.Focus();
                        return;
                    }
                }
            }
            newsHouseBO.IsActive = false;
            newsHouseBO.IsContact = true;
            newsHouseBO.ContactName = txtcontactname.Text;
            newsHouseBO.ContactAddress = txtcontactaddress.Text;
            newsHouseBO.ContactEmail = txtcontactEmail.Text;
            newsHouseBO.ContactPhone = txtcontactphone.Text;
            string addons = "", interiorAmenities = "", socialCulture = "";
            addons += txtbuidyear.Text + ",";
            addons += txtnhatam_vesinh.Text + ",";
            addons += txtso_phongngu.Text + ",";
            addons += cbnuocmay.Checked.ToString() + ",";
            addons += cbdonghodien.Checked.ToString() + ",";
            addons += txtduongtruocnha.Text;
            newsHouseBO.Addons = addons;
            interiorAmenities += cbthangmay.Checked.ToString() + ",";
            interiorAmenities += cbbaove.Checked.ToString() + ",";
            interiorAmenities += cbdauoto.Checked.ToString() + ",";
            interiorAmenities += cbsanvuon.Checked.ToString() + ",";
            interiorAmenities += cbdieuhoa.Checked.ToString() + ",";
            interiorAmenities += cbsanthuong.Checked.ToString() + ",";
            interiorAmenities += cbdienthoai.Checked.ToString() + ",";
            interiorAmenities += cbhoboi.Checked.ToString() + ",";
            interiorAmenities += cbnhabep.Checked.ToString() + ",";
            interiorAmenities += cbgaraoto.Checked.ToString() + ",";
            interiorAmenities += cbphongkhach.Checked.ToString();
            newsHouseBO.InteriorAmenities = interiorAmenities;
            socialCulture += cbcongvien.Checked.ToString() + ",";
            socialCulture += cbtrungtam_giaitri.Checked.ToString() + ",";
            socialCulture += cbmaugiao.Checked.ToString() + ",";
            socialCulture += cbtrungtam_thuongmai.Checked.ToString() + ",";
            socialCulture += cbdh_cd.Checked.ToString() + ",";
            socialCulture += cbbenhvien.Checked.ToString() + ",";
            socialCulture += cbcapba.Checked.ToString() + ",";
            socialCulture += cbcho.Checked.ToString() + ",";
            socialCulture += cbcaphai.Checked.ToString() + ",";
            socialCulture += cbkinhdoanh.Checked.ToString() + ",";
            socialCulture += cbcapmot.Checked.ToString() + ",";
            socialCulture += cbkhudantri.Checked.ToString();
            newsHouseBO.SocialCulture = socialCulture;
            bool checkerror = true;
            try
            {
                newsHouseBO.Save();
                if (pn_quangcao.Visible == true)
                {
                    if (checkqc == true)
                    {
                        qcdetailbo = LocationAdvertisementDetailBO.GetAdvertisementDetaiBO_ByIDNewsHouses(newsHouseBO.NewsHouseID);
                        boqc = LocationAdvertisementBO.GetLocationAdvertisementBO(Convert.ToInt32(qcdetailbo.LocationAdversitementID));
                        qcdetailbo = boqc.LocationAdvertisementDetailBOList.Single(a => a.NewsHouseID == newsHouseBO.NewsHouseID);
                        if (location_parrent != Convert.ToInt32(dlkhuvuc_qc.SelectedValue))
                        {
                            qcdetailbo.NewsHouseID = null;
                            boqc.Save();
                        }
                        else if (location_detail_inweb != dlchitiet.SelectedValue)
                        {
                            qcdetailbo.NewsHouseID = null;
                            boqc.Save();
                        }
                    }
                    //qcdetailbo = LocationAdvertisementDetailBO.GetAdvertisementDetaiBO_ByIDNewsHouses(newsHouseBO.NewsHouseID);
                    boqc = LocationAdvertisementBO.GetLocationAdvertisementBO(Convert.ToInt32(dlkhuvuc_qc.SelectedValue));
                    qcdetailbo = boqc.LocationAdvertisementDetailBOList.Single(a => a.LocationInWeb == dlchitiet.SelectedValue);
                    qcdetailbo.NewsHouseID = newsHouseBO.NewsHouseID;
                    boqc.Save();
                    changeChiTietQuangCao();
                }
               
                var ss = "thanhcong";
                Session["managernews"] = ss;
                checkerror = false;               
            }
            catch
            {
                deleteListImage();
                deleteExitsImage(newsHouseBO.UrlImageAdversitement);
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Sửa thất bại !')", true);
            }
            if (checkerror == false)
            {
                Response.Redirect("QuanLyCaNhan.aspx");
                return;
            }

        }

        protected void btngiahan_Click(object sender, EventArgs e)
        {
            NewsHouseBO newsH = NewsHouseBO.GetNewsHouseBO(int.Parse(mode));
            newsH.IsExtension = true;
            newsH.PostDate = DateTime.Now;
            newsH.UpdatedDate = DateTime.Now;
            newsH.ExtensionDate = DateTime.Now;
            newsH.NumExtension += 1;
            newsH.ExpireDate = DateTime.Now.AddDays(double.Parse(dlgiahan.SelectedValue));
            try
            {
                newsH.Save();
                Response.Redirect("DangTin.aspx?id=" + mode + "&giahan=true");
            }
            catch
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Gia hạn không thành công !')", true);
                return;
            }
        }

        protected void btnhuygiahan_Click(object sender, EventArgs e)
        {
            pn_giahan.Visible = false;
        }

        protected void lbtgiahan_Click(object sender, EventArgs e)
        {
            OptionBO optionbo;
            optionbo = OptionBO.GetNameOptionBO("SoLanGiaHanTinNhaDat");

            if (Convert.ToInt32(optionbo.OptionValue) <= newsHouseBO.NumExtension)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Tin này đã hết quyền gia hạn !')", true);
                return;
            }
            else
            {
                pn_giahan.Visible = true;
                lblsolangiahan.Text = newsHouseBO.NumExtension.ToString();
                btngiahan.Focus();
            }
        }

        protected void btnxoa_Click(object sender, EventArgs e)
        {
            try
            {
                int newsid = Convert.ToInt32(mode);
                NewsHouseBOList.Delete_ByKey(newsid);
                NewsHouseBO newshBO = NewsHouseBO.GetNewsHouseBO(newsid);
                if (newshBO.UrlImage != "")
                {
                    var array_listImage = newshBO.UrlImage.Split('/');
                    foreach (var detail in array_listImage)
                    {
                        deleteExitsImage(detail);
                    }
                }
                NewsHouseBO.DeleteNewsHouseBO(newsid);
                Response.Redirect("QuanLyCaNhan.aspx");
            }
            catch
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Xoá tin thất bại !')", true);
            }
        }

        protected void btnxemtruoc_Click(object sender, EventArgs e)
        {

        }

        protected void btnketthuc_Click(object sender, EventArgs e)
        {
            try
            {
                int newsid = Convert.ToInt32(mode);
                NewsHouseBO newshBO = NewsHouseBO.GetNewsHouseBO(newsid);
                newshBO.IsActive = false;
                newshBO.Save();
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Kết thúc đăng tin thành công!!!')", true);
            }
            catch
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Kết thúc đăng tin thất bại!!!')", true);
                return;
            }
        }

        protected void btngiahantin_Click(object sender, EventArgs e)
        {
            NewsHouseBO newsH = NewsHouseBO.GetNewsHouseBO(int.Parse(mode));
            newsH.IsExtension = true;
            newsH.PostDate = DateTime.Now;
            newsH.UpdatedDate = DateTime.Now;
            newsH.ExtensionDate = DateTime.Now;
            newsH.NumExtension += 1;
            newsH.ExpireDate = DateTime.Now.AddDays(double.Parse(dlthoigiangiahanhai.SelectedValue));
            try
            {
                newsH.Save();
                Response.Redirect("DangTin.aspx?id=" + mode + "&giahan=true");
            }
            catch
            {
                pn_error.Visible = true;
            }
        }
    }
}